package org.jeecg.modules.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.common.FileTypeChecker;
import org.jeecg.modules.common.GetUserInfoUtils;
import org.jeecg.modules.entity.DbFile;
import org.jeecg.modules.service.IDbFileService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: db_file
 * @Author: jeecg-boot
 * @Date:   2024-06-21
 * @Version: V1.0
 */
//@Api(tags="db_file")
@RestController
@RequestMapping("/dbFile")
@Slf4j
public class DbFileController extends JeecgController<DbFile, IDbFileService> {
	@Autowired
	private IDbFileService dbFileService;


	 /**
	  * 本地文件上传（记录数据库）
	  * @param request
	  * @param response
	  * @return
	  */
//	 @ApiOperation(value="文件上传", notes="文件上传")
	 @PostMapping(value = "/upload")
	 public Result<DbFile> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		 Result<DbFile> result = new Result<DbFile>();
		 String savePath = "";
		 String bizPath = request.getParameter("biz");

		 if (oConvertUtils.isNotEmpty(bizPath)) {
			 if(bizPath.contains(SymbolConstant.SPOT_SINGLE_SLASH) || bizPath.contains(SymbolConstant.SPOT_DOUBLE_BACKSLASH)){
				 throw new JeecgBootException("上传目录bizPath，格式非法！");
			 }
		 }else {
			 throw new JeecgBootException("必须指定上传目录");
		 }

		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 // 获取上传文件对象
		 MultipartFile file = multipartRequest.getFile("file");

		 String fileName = CommonUtils.getFileName(file.getOriginalFilename());
		 log.info("上传文件名:{}",fileName);
		 String extName = FileUtil.extName(fileName);
		 FileTypeChecker.FileType  fileTypeEnum = FileTypeChecker.checkFileType(fileName);

		 String fileType = fileTypeEnum.getValue();
		 log.info("上传文件后缀:{}",extName);
		 long fileSize = file.getSize();
		 log.info("上传文件大小:{}",fileSize);

		 String uuid =UUIDGenerator.generate();

		 savePath = OssBootUtil.upload(file,bizPath);

		 if(StringUtils.isBlank(savePath)){
			 result.setMessage("上传失败！");
			 result.setSuccess(false);
			 return result;
		 }
		 Date now = new Date();
		 DbFile dbFile = new DbFile();
		 dbFile.setId(uuid);
		 dbFile.setFileName(fileName);
		 dbFile.setFileNameExt(extName);
		 dbFile.setFileSize(fileSize);
		 dbFile.setFilePath(savePath);
		 dbFile.setFileCatalog(fileType);
		 dbFile.setCreateTime(now);
		 dbFile.setCreateBy(GetUserInfoUtils.getLoginUserName());
		 dbFileService.save(dbFile);
		 result.setResult(dbFile);
		 result.setMessage(savePath);
		 result.setSuccess(true);
		 return result;
	 }
	/**
	 * 分页列表查询
	 *
	 * @param dbFile
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "db_file-分页列表查询")
//	@ApiOperation(value="db_file-分页列表查询", notes="db_file-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DbFile>> queryPageList(DbFile dbFile,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<DbFile> queryWrapper = QueryGenerator.initQueryWrapper(dbFile, req.getParameterMap());
		Page<DbFile> page = new Page<DbFile>(pageNo, pageSize);
		IPage<DbFile> pageList = dbFileService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param dbFile
	 * @return
	 */
	@AutoLog(value = "db_file-添加")
//	@ApiOperation(value="db_file-添加", notes="db_file-添加")
	//@RequiresPermissions("org.jeecg.modules:db_file:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DbFile dbFile) {
		dbFileService.save(dbFile);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param dbFile
	 * @return
	 */
	@AutoLog(value = "db_file-编辑")
//	@ApiOperation(value="db_file-编辑", notes="db_file-编辑")
	//@RequiresPermissions("org.jeecg.modules:db_file:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DbFile dbFile) {
		dbFileService.updateById(dbFile);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "db_file-通过id删除")
//	@ApiOperation(value="db_file-通过id删除", notes="db_file-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:db_file:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		dbFileService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "db_file-批量删除")
//	@ApiOperation(value="db_file-批量删除", notes="db_file-批量删除")
	//@RequiresPermissions("org.jeecg.modules:db_file:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.dbFileService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "db_file-通过id查询")
//	@ApiOperation(value="db_file-通过id查询", notes="db_file-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DbFile> queryById(@RequestParam(name="id",required=true) String id) {
		DbFile dbFile = dbFileService.getById(id);
		if(dbFile==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(dbFile);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param dbFile
    */
    //@RequiresPermissions("org.jeecg.modules:db_file:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DbFile dbFile) {
        return super.exportXls(request, dbFile, DbFile.class, "db_file");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("db_file:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DbFile.class);
    }

}
